package com.starbaba.loanorder.view;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.base.common.database.BaseDao;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.loanorder.model.LoanOrderModel;
import com.starbaba.loanorder.service.LoanOrderService;
import com.starbaba.loanorder.service.impl.LoanOrderServiceImpl;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.util.ExcelOperateUtil;

@SuppressWarnings({ "serial", "unchecked", "rawtypes"})
public class LoanOrderAction extends BaseAction implements ModelDriven<LoanOrderModel> {

	@SuppressWarnings("deprecation")
	final BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private File upload;
	private String savePath;
	private String uploadFileName;
	private String uploadContentType;

	private String fileName;
	private InputStream input;

	private LoanOrderModel model;
	private LoanOrderService service = new LoanOrderServiceImpl();

	@Override
	public LoanOrderModel getModel() {
		if (model == null) {
			model = new LoanOrderModel();
		}
		return model;
	}

	public String show() {
		return SUCCESS;
	}
	

	/**
	 * 订单列表
	 */
	public void getLoanOrderList() {

		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();

		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List list = service.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 查询订单请求JSON
	 */
	public void getLoanOrderRequestList() {
		
		parsePageRequest();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List list = service.getRequestList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		pageResponse.setITotalRecords(list.size());
		pageResponse.setITotalDisplayRecords(list.size());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	public String exportDetailCSV() throws UnsupportedEncodingException {

		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);

		pageRequest.setIDisplayStart(-1);
		pageRequest.setIDisplayLength(-1);
		pageRequest.setOrderby("createtime");
		pageRequest.setOrder("desc");

		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List<LoanOrderModel> list = service.getDataList(start, length, pageResponse, paramsMap);
		String value = service.exportLoanOrderList(list);
		input = new ByteArrayInputStream(value.getBytes("GBK"));
		fileName = System.currentTimeMillis() + ".csv";
		return ActionSupport.SUCCESS;
	}
	

	/**
	 * 读取合作方回传订单Excel
	 * 
	 * @return
	 * @throws Exception
	 */
	public void uploadExcelData() throws Exception {

		parsePageRequest();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);

		try {
			File file = upload;
			String type = (String) paramsMap.get("type"); // 合作方类型
			String fileSuffix = (String) paramsMap.get("suffix");

			@SuppressWarnings("deprecation")
			BaseDao dao = new BaseDao(Constant.POOL_LIFE);

			if (file.exists()) {
				String fileName = file.getAbsolutePath();
				// 临时文件后缀名改为源文件后缀名
				fileName = fileName.replace(".tmp", "." + fileSuffix.toLowerCase());
				file.renameTo(new File(fileName));
				file = new File(fileName);
			}

			ExcelOperateUtil poi = new ExcelOperateUtil();
			String[][] result = poi.getData(file);

			int rows = 1; // Excel表格的第几行
			int success = 0;
			for (String[] row : result) {
				if (rows == 1) {
					rows++;
					continue;
				}

				String orderId = row[1]; // 订单ID
				String mobnum = row[2]; // 客户手机号
				String status = row[3]; // 订单状态
				String loanAmount = row[4]; // 实际放款金额
				String loanPeroid = row[5]; // 贷款期限
				String tranTime = row[6]; // 审核时间
				String settleAmount = row[7]; // 结算金额

				if (StringUtils.isEmpty(orderId)) {
					continue;
				}

				if (StringUtils.isEmpty(mobnum)) {
					continue;
				}

				if (StringUtils.isEmpty(status)) {
					continue;
				}
			
				if (StringUtils.isEmpty(tranTime)) {
					continue;
				}
                
				LoanOrderModel order = new LoanOrderModel();
				order.setId(Long.parseLong(orderId));
				order.setType(Integer.parseInt(type));
				order = dao.get(order, new String[] { "id", "type" });
				
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				if (order != null) {
					LoanOrderModel updateOrder = new LoanOrderModel();
					updateOrder.setId(Long.parseLong(orderId));
					updateOrder.setType(Integer.parseInt(type));
					updateOrder.setMobnum(mobnum);
					if ("0".equals(status)) {
						updateOrder.setStatus(4); // 审核失败,合作方取消
					} else if ("1".equals(status)) {
						updateOrder.setStatus(6); // 审核通过
					}
					if (!StringUtils.isEmpty(loanAmount)) {
						updateOrder.setLoan_amount(Double.parseDouble(loanAmount));
					}
					if (!StringUtils.isEmpty(loanPeroid)) {
						updateOrder.setPeroid(loanPeroid);
					}
					if (!StringUtils.isEmpty(settleAmount)) {
						updateOrder.setSettle_amount(Double.parseDouble(settleAmount));
					}
					updateOrder.setTransaction_time(format.parse(tranTime));
					dao.update(updateOrder, new String[] { "id", "type" });
					success ++;
				}
				rows++;
			}
			JsonObject resultJson = new JsonObject();
			resultJson.addProperty("total", result.length -1);
			resultJson.addProperty("success", success);
			sendJsonMessage(resultJson.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * API订单统计
	 */
	public void getStatLoanOrderList() {

		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();

		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List list = service.getStatDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			LogService.error(e);
		}
	}
	
	
	/**
	 * API订单统计导出
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String exportStatCSV() throws UnsupportedEncodingException {

		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);

		pageRequest.setIDisplayStart(-1);
		pageRequest.setIDisplayLength(-1);
		pageRequest.setOrderby("createtime");
		pageRequest.setOrder("desc");

		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List<LoanOrderModel> list = service.getStatDataList(start, length, pageResponse, paramsMap);
		String value = service.exportStatLoanOrderList(list);
		input = new ByteArrayInputStream(value.getBytes("GBK"));
		fileName = System.currentTimeMillis() + ".csv";
		return ActionSupport.SUCCESS;
	}

	public String getFileName() {
		return fileName;
	}

	public InputStream getInput() {
		return input;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
}
